from rest_framework.views import exception_handler
from rest_framework import status

from utils.logging import log
from .response import CommonResponse


def common_exception_handler(exc, context):
    response = exception_handler(exc, context)
    # 记录日志: context['view']  是TextView的对象，想拿出这个对象对应的类名
    log.error(f'{context.get("view").__class__.__name__}:{exc}')
    if not response:
        obj = CommonResponse(code=2000, messages='error', results=str(exc),
                             status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    else:
        obj = CommonResponse(code=2000, messages='error', results=response.data,
                             status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    return obj
